package com.lagou.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class CookieFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        MultiValueMap<String, HttpCookie> cookies = exchange.getRequest().getCookies();
        String hostString = exchange.getRequest().getRemoteAddress().getHostString();
        RequestPath path = exchange.getRequest().getPath();
        if(path.value().substring(0,10).equals("/user/info")&&!cookies.containsKey("token")){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "您还没有登录，请先登录";
            log.debug("=====>IP:" + hostString + " 无token，将被拒绝访问！");
            DataBuffer dataBuffer = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(dataBuffer));

        }
        return chain.filter(exchange);
    }
}
